#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys

def main():
    if len(sys.argv) != 2:
        print "invalid number of args: ./inline_forms.py filename"
        exit(-1)
    input_file = sys.argv[1]


    lines = open(input_file).readlines()

    tag_prefix = "// tags:"
    news_lines = []
    request_start = False
    for line in lines:
        line = line.strip()
        new_line = line

        if not request_start:
            if re.search("type (\w+)Request struct {", line):
                request_start = True
        else:
            if line.startswith("XXX_") or line.startswith("}"):
                request_start = False
            elif line.startswith("//"):
                pass
            else:
                match = re.search("json:\"(.*?)\"", line)
                if match:
                    form_tag = (" form:\"%s\"" % match.group(1))
                    if news_lines[-1].startswith(tag_prefix):
                        print news_lines[-1]
                        tags = news_lines[-1][len(tag_prefix):]
                        form = parse_tag(tags, "form")
                        if form:
                            form_tag = (" form:\"%s\"" % form)

                        print form_tag
                    new_line = line[0:match.start(0)] + match.group(0) + form_tag + line[match.end(0):]
        news_lines.append(new_line)
    open(input_file, "w").write("\n".join(news_lines))

def parse_tag(tag, key):
    while tag:
        # skip leading space
        i = 0
        while i < len(tag) and tag[i] == ' ':
            i = i + 1
        tag = tag[i:]
        if not tag:
            break
        i = 0
        while i < len(tag) and tag[i] > ' ' and tag[i] != ':' and tag[i] != '"' and tag[i] != 0x7f:
            i = i + 1
        if i == 0 or i + 1 >= len(tag) or tag[i] != ':' or tag[i+1] != '"':
            break
        name = tag[0:i]
        tag = tag[i+1:]
        # scan quoted string to find value
        i = 1
        while i < len(tag) and tag[i] != '"':
            if tag[i] == '\\':
                i = i + 1
            i = i + 1
        if i >= len(tag):
            break
        qvalue = tag[:i+1]
        tag = tag[i+1:]
        if key == name:
            if len(qvalue) > 2:
                if qvalue[0] == '"' and qvalue[-1] == '"':
                    qvalue = qvalue[1:-1]
                elif qvalue[0] == '\'' and qvalue[-1] == '\'':
                    qvalue = qvalue[1:-1]
        return qvalue
    return ""

if __name__ == "__main__":
    main()
